package daoLivraria;

import java.sql.*;

public class DataSourceDAO {

    private static String url = "jdbc:postgresql://localhost/bdlivraria";
    private static String usuario = "postgres";
    private static String senha = "postgres";
    private static Connection con = null;

    public static Connection getConnection() {
        if (DataSourceDAO.con != null) {
            System.out.println("RETORNO DE CONEXAO JA CRIADA");
            return DataSourceDAO.con;
        } else {
            try {
                Class.forName("org.postgresql.Driver");
            } catch (ClassNotFoundException e1) {
                System.out.println("Driver JDBC nao carregado");
                return null;
            }
            try {
                DataSourceDAO.con = DriverManager.getConnection(url, usuario, senha);

                System.out.println("RETORNO DE NOVA CONEXAO");
                return DataSourceDAO.con;

            } catch (SQLException sql1) {
                System.out.println("Erro em base de dados: " + sql1.toString());
                return null;
            }

        }
    }

    public static Connection getConnection2() {
        if (DataSourceDAO.con != null) {
            try {
                if (!DataSourceDAO.con.isValid(2)) {
                    DataSourceDAO.con = DriverManager.getConnection(url, usuario, senha);

                    System.out.println("RETORNO DE NOVA CONEXAO APOS TIMEOUT");
                    return DataSourceDAO.con;
                }
            } catch (SQLException sql1) { }
            System.out.println("RETORNO DE CONEXAO JA CRIADA");
            return DataSourceDAO.con;
        } else {
            try {
                Class.forName("net.sourceforge.jtds.jdbc.Driver");
            } catch (ClassNotFoundException e1) {
                System.out.println("Driver JDBC nao carregado");
                return null;
            }
            try {
                DataSourceDAO.con = DriverManager.getConnection(url, usuario, senha);

                System.out.println("RETORNO DE NOVA CONEXAO");
                return DataSourceDAO.con;

            } catch (SQLException sql1) {
                System.out.println("Erro em base de dados: " + sql1.toString());
                return null;
            }

        }
    }


}
